<?php
class bcategory{
	private $type;
	private $words = Array() ;
	private $pfile;
	private $numdocs = 0;
	private $train;
	public function __construct($type="default", $train=false){
		$this->train = $train;
		$this->setTypeandLoad($type);
		if (!$train)
			$this->buildDict();
	}
	public function getType(){
		return $this->type;
	}
	public function inTrainning(){
		return $this->train;
	}
	private function setTypeandLoad($type){
		$this->type = $type;
		$this->pfile = BAYES_CAT_PATH . $this->type . ".dict"; 
		if (!file_exists($this->pfile)){
			fopen($this->pfile,"w");
		}
	}
	private function buildDict(){
		$config= parse_ini_file($this->pfile,true);
		$this->words = $config["words"];
		$this->numdoc = $config["numdoc"]["total"];
	}
	public function getTotalDoc(){
		return $this->numdoc;
	}
	public function getWord($word){
			return (array_key_exists($word, $this->words))?$this->words[$word]:0;
	}
	public function setWord($word,$value){
			$this->words[$word]=$this->getWord($word)+$value;
	}
	public function calculate($numdocs){
		$this->numdocs = $numdocs;
		// this function is using when its in trainning and make $this->words/numdoc to get basic probabilits.
		foreach ($this->words as $word =>$value){
			$this->words[$word] = (($value / $numdocs) > 1)?1: ($value / $numdocs);
		}
	}
	public function Save($as = null){
		if (!is_null($as))
			$this->setTypeandLoad($as);
		$confcontent = "[numdoc] \n total= {$this->numdocs}\n[words]\n";
		foreach ($this->words as $word => $value)
			$confcontent .= " {$word}= {$value}\n";
			$f = fopen($this->pfile, 'w');
			fwrite($f, $confcontent);
	}
}